#------------------------------------------------------------------------------
# Import libraries
#------------------------------------------------------------------------------

rm(list=ls())
library(LalRUtils)
libreq(tidyverse, data.table, zoo, tictoc, fst, fixest, PanelMatch, patchwork,
       rio, magrittr, janitor, did, panelView, ggiplot, tictoc, binsreg, interflex)
set.seed(42)
theme_set(lal_plot_theme())

#------------------------------------------------------------------------------




#------------------------------------------------------------------------------
# Define Paths
#------------------------------------------------------------------------------

# R studio
setwd( dirname(rstudioapi::getActiveDocumentContext()$path) )
# R default : unccoment if you use default R
# setwd(getSrcDirectory(function(){})[1])

#------------------------------------------------------------------------------




#------------------------------------------------------------------------------
# Load Data
#------------------------------------------------------------------------------

vcf <- fread("vcf_data_complete.csv", sep = ",")
setnames( vcf, "d", "D")
vcf_data <- copy( vcf )
gfc <- fread("gfc_dta.csv" )


#------------------------------------------------------------------------------




# %% VCF prep
if (exists("vcf_data")) {
  vcf = vcf_data[year >= 1995]
  rm(vcf_data)
}
vcf[, t := year - 1995]
(ex_ante_med = quantile(vcf$cover_1990, 0.5))
above_med = vcf[cover_1990 > ex_ante_med]
above_med[, never_treated := max(D) == 0, cellid]



# %% GFC regressions
# 2wFE
m00 = feols(def_ha ~ D | village + year, cluster = "block", gfc[pref == 1])
# 2wFE + state year FEs
m01 = feols(def_ha ~ D | village + styear, cluster = "block",
            gfc[gfc3 == TRUE & pref == 1])
# with effective sample for cols 3, 4
m003 = feols(def_ha ~ D | village + village[t] + styear, cluster = "block",
             gfc[gfc3 == TRUE & pref == 1])

# %% control means for table
gfc[, ever_treated := max(D), .(village)]
ctrl_mean  = round(gfc[pref == 1 & ever_treated == 0 & pesa_exposure == 0, mean(def_ha)], 2)
ctrl_mean2 = round(gfc[pref == 1 & gfc3 == T & ever_treated == 0 & pesa_exposure == 0, mean(def_ha)], 2)
treat_mean  = round(gfc[pref == 1 & ever_treated == 1 & pesa_exposure == 0, mean(def_ha)], 2)
treat_mean2 = round(gfc[pref == 1 & gfc3 == T & ever_treated == 1 & pesa_exposure == 0, mean(def_ha)], 2)
# VCF regressions
# %% above median sample - cutoff in 1990
controls_pre1 = above_med[never_treated == 1 & year < first_pesa_exposure, mean(forest_index)]
treat_pre1    = above_med[never_treated == 0 & year < first_pesa_exposure, mean(forest_index)]
# %%
m0 = feols(forest_index ~ D | cellid + year,  	  data = above_med, cluster = "blk")
m1 = feols(forest_index ~ D | cellid + styear,    data = above_med, cluster = "blk")
m3 = feols(forest_index ~ D | cellid[t] + styear, data = above_med, cluster = "blk")

# %% export
treatmap =c(
  # GFC
  "def_ha"       = "Annual Deforestation in Hectares",
  "village"      = "Village",
  "village[t]"   = "Village + Village TT",
  # VCF
  "forest_index" = "Forest Cover Index",
  "green_index"  = "Non-forest green index",
  "built_index"  = "Non-forest index",
  "cellid"       = "Pixel",
  "cellid[t]"    = "pixel + pixel TT",
  # both
  "yr"           = "Year",
  "year"         = "Year",
  "styear"       = "State $\\times$ Year",
  "D"            = "PESA $\\times$ Scheduled",
  "block"        = "Block",
  "blk"          = "Block"
)
# %%
desc = "Deforestation and Forest cover index"
fn = "regs_all_main"; lab = "tab:regs_all_main";
mods = list(m0, m1, m3, m00, m01, m003)
etable(mods, 
       
       fixef_sizes = T, 
       fixef_sizes.simplify = F,
       fitstat = ~ n, 
       dict = treatmap)

# %%
fitstat_register("n_new", function(x) summary( x )$nobs , 
                 "\\# Observations")
etable(mods,
       style.tex = style.tex(main = "base", 
                             depvar.title = "", 
                             model.title = "", 
                             var.title = "\\midrule", 
                             slopes.title = "\\midrule \\emph{Time Trends}", 
                             yesNo = c("$\\checkmark$", ""), 
                             signif.code = NA, 
                             line.bottom = "\\midrule \\midrule"),
       signif.code = NA,
       fixef_sizes = T, 
       fixef_sizes.simplify = F,
       fitstat = c( "n_new", "r2" ), 
       tex = TRUE,
       dict = treatmap,
       label = lab,
       title = glue::glue("{desc} regression estimates (ex-ante median cutoff)"),
       notes = "\\emph{Notes:} Standard errors are clustered at the block level and reported in parentheses.",
       extralines=list(
         "\\midrule \\emph{Summary Statistics}" = c("", "","","","","" ),
         "Mean Y (Non-Sch)"= c(rep(controls_pre1, 3), 
                               ctrl_mean, ctrl_mean2, ctrl_mean2),
         "Mean Y (Sch )"   = c( rep( treat_pre1, 3 ), 
                                treat_mean, treat_mean2, treat_mean2),
         "Dataset"     = c( rep( "VCF", 3 ), rep( "GFC", 3 ) ),
         "Timespan"    = c( rep( "1995-2017", 3 ), rep( "2001-2017", 3 ) )
       ),
       file = "main_table1.tex", 
       replace = TRUE
)
